<!--
 * @description  :展示物品信息
 * @descriptionDetail:展示物品信息
 * @copyright    : 浙江烟草
 * @author       : sy
 * @create       : 2022-08-26 10:57:44
-->
<template>
  <view class="page">
    <view class="">
      <view style="margin: -6px -16px 0px -16px;">
        <u-gap :height="$theme.cm_gap_height" :bg-color="$theme.cm_gap_color"></u-gap>
      </view>
      <view class="m-flex-row">
        <view style="width: calc(100% - 30px);">
          <form-section title="物品信息登记" iconColorClass="u-success"></form-section>
        </view>
        {{ choseType }}
        <view v-if="choseType !== 'caseMap'" style="display: flex;flex-direction: row;align-items: center;">
          <u-icon
            name="baocun"
            color="primary"
            custom-prefix="csbi-icon"
            style="margin-right: 20rpx;"
            size="40"
            v-if="hasEdit"
            @click="saveGoods()"
          ></u-icon>
          <u-icon name="plus-circle" color="primary" size="40" v-if="hasAdd && !isAll" @click="addGoods()">
          </u-icon>
        </view>
      </view>
      <!-- 先行物品登记清单 -->
      <view class="m-flex-row">
        <view class="u-font-28 total-tip">
          合计(总金额)<text>
            {{ goodsTotalPrice }}
          </text>元
        </view>
        <view class="u-font-28 total-tip">
          合计(数量)<text>
            {{ goodsTotalNum }}
          </text>条
        </view>
      </view>
      <view class="m-flex-row" style="padding: 20rpx 0;" v-if="showSearch">
        <u-search placeholder="请输入品规名称" :show-action="false" v-model="keyWord" @change="changeKeyWord">
        </u-search>
      </view>
      <view class="">
        <u-table font-size="26" style="border-left: none;">
          <u-tr class="u-tr border-left">
            <u-th class="u-th" width="12%">
              {{ isAll ? "提交人":"序号" }}
            </u-th>
            <u-th width="45%" class="u-th">
              品牌规格
            </u-th>
            <u-th class="u-th">
              条数
            </u-th>
            <u-th class="u-th">
              金额
            </u-th>
            <u-th class="u-th" v-if="hasDel">
              操作
            </u-th>
          </u-tr>
          <me-list
            :normalScrollView="true"
            :i="0"
            :height="getListHeight()"
            :loadData="loadData"
            ref="mescrollRef0"
          >
            <u-tr class="u-tr border-left" :class="[d.index == 0 ? 'border-Top' : '']" slot-scope="d">
              <u-td class="u-td" width="12%">
                {{ isAll ? d.data.creator : d.index+1 }}
              </u-td>
              <u-td width="45%" class="u-td" style="color: #2979ff;">
                <text @click="itemDetail(d.data)">
                  {{ d.data.goodsName }}<!-- {{ d.data.spec ? d.data.spec + 'mm' : '' }} -->
                </text>
              </u-td>
              <u-td clas="u-td">
                <!-- 移动端案件通知书已经完成还能编辑物品信息的问题  zx s -->
                <u-input
                  style="display: contents;"
                  type="digit"
                  placeholder=""
                  input-align="center"
                  :disabled="d.data.goodsRegUuid"
                  :clearable="false"
                  v-model="d.data.qty"
                  @blur="handleBlur(d.data)"
                ></u-input>
                        <!-- 移动端案件通知书已经完成还能编辑物品信息的问题  zx e -->
              </u-td>
              <u-td class="u-td">
                <!-- 物品金额 -->
                {{ priceInfo(d.data) }}
              </u-td>
              <u-td class="u-td" style="color: #fa3534;" v-if="hasDel">
                <text @click="delTmp(d.data)">
                  删除
                </text>
              </u-td>
            </u-tr>
          </me-list>
        </u-table>
      </view>
    </view>
    <u-popup mode="bottom" height="42%" v-model="detailShow">
      <view class="content" style="padding: 40rpx;">
        <view style="position: fixed;top: 0;width: 100%;height: 30rpx;background-color: white;"></view>
        <view style="padding-bottom: 120rpx;">
          <u-row gutter="16">
            <u-col span="12">
              <text style="font-size: 30rpx;">
                品牌品规: {{ detailData.goodsName }}
              </text>
            </u-col>
          </u-row>
          <u-row gutter="16">
            <u-col span="6">
              <text style="font-size: 24rpx;color: #666666;">
                数量(条): {{ detailData.qty }}
              </text>
            </u-col>
            <u-col span="6">
              <text style="font-size: 24rpx;color: #666666;">
                支每条: {{ detailData.unitQty }}
              </text>
            </u-col>
          </u-row>
          <u-row gutter="16">
            <u-col span="6">
              <text style="font-size: 24rpx;color: #666666;">
                单位: {{ detailData.unit }}
              </text>
            </u-col>
            <u-col span="6">
              <text style="font-size: 24rpx;color: #666666;">
                单价: {{ detailData.price }}
              </text>
            </u-col>
          </u-row>
          <u-row gutter="16">
            <u-col span="6">
              <text style="font-size: 24rpx;color: #666666;">
                金额: {{ detailData.amt }}
              </text>
            </u-col>
            <u-col span="6">
              <text style="font-size: 24rpx;color: #666666;">
                物品性质: {{ getDicName($u.dic.DIC_KEYS.GOODS_PROP_SUBTYPE, detailData.propSubtype) }}
              </text>
            </u-col>
          </u-row>
          <u-row gutter="16">
            <u-col span="6">
              <text style="font-size: 24rpx;color: #666666;">
                环节: {{ getDicName($u.dic.DIC_KEYS.GET_NODE, detailData.getNode) }}
              </text>
            </u-col>
          </u-row>
          <u-row gutter="16">
            <u-col span="12">
              <text style="font-size: 24rpx;color: #666666;">
                来源地: {{ detailData.sourceAddrName }}
              </text>
            </u-col>
          </u-row>
          <u-row gutter="16">
            <u-col span="12">
              <text style="font-size: 24rpx;color: #666666;">
                去向地: {{ detailData.toAddrName }}
              </text>
            </u-col>
          </u-row>
        </view>
        <view
          class="nwidth"
          style="padding: 10rpx;bottom: 20rpx;position: fixed;background-color: white;"
          v-show="hasAdd"
          v-if="$u.test.isEmpty(detailData.goodsRegUuid)"
        >
          <u-button size="default" type="error" plain @click="delGoodsItem">
            删除记录
          </u-button>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
import mescrollList from "@/components/mescroll_list.vue";
import caseService from "@/service/case/case.service";
import FormSection from "@/components/form-section.vue";
export default {
  name: "ShowGoodsInfo",
  components: {
    "me-list": mescrollList,
    FormSection,
  },
  props: {
    caseUuid: {
      type: String,
      default: "",
    },
    caseCode: {
      type: String,
      default: "",
    },
    hasEdit: {
      type: Boolean,
      default: false, // 是否可以编辑 默认不可以
    },
    hasAdd: {
      type: Boolean,
      default: false,
    },
    height: { // 不能设置100% 之类的。 设置具体 px 数值
      type: Number,
      default: 350, // 默认300 px
    },
    params: { // 默认接口的请求参数
      type: Object,
      default: new Object(),
    },
    isAll: { // 是否显示全部(主办人、协办人等)数据
      type: Boolean,
      default: false,
    },
    showSearch: {
      type: Boolean,
      default: false,
    },
    dataFromInit: { // 自定义数据来源
      type: Function,
      default: undefined,
    },
    hasDel: {
      type: Boolean,
      default: false,
    },
    choseType: {
      type: String,
      default: '',
    }
  },
  data() {
    return {
      goodsList: [],
      keyWord: "",
      detailShow: false,
      detailData: {},
      showAll: false,
      caseClueList: [],
    }
  },
  computed: {
    goodsCount() {
      return this.goodsList.length;
    },
    goodsTotalNum() {
      let num = 0;
      for (let i = 0; i < this.goodsList.length; i++) {
        try {
          num += Number(this.goodsList[i].qty);
        } catch (er) {
          console.log(er);
        }
      }
      if (this.$u.test.digits(num)) { // 是整数
        return num;
      } else { // 不是整数保留2位小数
        return Number(num.toFixed(2));
      }
    },
    goodsTotalPrice() {
      let totalPrice = 0;
      let realTxt = 0;
      for (let i = 0; i < this.goodsList.length; i++) {
        try {
          let qty = Number(this.goodsList[i].qty);
          let price = Number(this.goodsList[i].price);
          totalPrice += qty * price;
          if (this.$u.test.digits(totalPrice)) { // 是整数
            realTxt = totalPrice;
          } else { // 不是整数保留2位小数
            realTxt = Number(totalPrice.toFixed(2));
          }
        } catch (er) {
          console.log(er);
          realTxt = 0;
        }
      }
      return realTxt == 0 ? "" : realTxt;
    },
  },
  watch: {
    isAll(newValue, oldValue) {
      this.showAll = newValue;
    },
    dataFromInit(newValue, oldValue) {
      this.refreshData(false);
    },
  },

  created() {

  },
  methods: {
    handleBlur(data) {
      data.amt = data.price * Number(data.qty);
    },
    priceInfo(d) {
      console.log(d);
      try {
        return (d.price * d.qty).toFixed(2)
        // return (d.price * d.qty).toFixed(1)
      } catch (err) {
        console.log(err)
      }
      return '';
    },
    addGoods: function() {
      this.setRouteParam({
        goodList: this.goodsList,
        casePropList: this.params.casePropertyRelList,
        params: this.params,
        showAll: this.showAll,
      });
      this.$u.route({
        url: "/pages/case/goods/addGoodsInfo",
        type: 'to',
        params: {
          caseUuid: this.caseUuid,
          caseCode: this.caseCode,
        },
      });
    },
    enterInformation(d) {
      this.setRouteParam(d)
      this.$u.route("pages/case/components/inkjetCodeEnter")
    },
    saveGoods() {
      this.$modal.showLoading("正在保存...");
      caseService.saveGoodsInfo(this.caseUuid, this.showAll ? "" : '0', this.goodsList).then(res => {
        this.$modal.hideLoading();
        if (res.success) {
          this.$u.toast('保存成功');
          if (this.dataFromInit) { // 表示用的外部数据 需要提示外部重新拉取最新数据
            this.$emit('saveRefresh', true);
          } else {
            this.keyWord = "";
            this.$emit('saveRefresh', true);
            this.$refs['mescrollRef0'].resetList(true);
          }
        } else {
          this.$modal.alert("保存失败:" + res.msg);
          this.$emit('saveRefresh', false);
        }
      }).catch(err => {
        this.$modal.hideLoading();
        this.$modal.alert("保存失败:" + err);
        this.$emit('saveRefresh', false);
      });
    },
    itemDetail(obj) {
      this.detailData = obj;
      this.detailShow = true;
    },
    delGoodsItem() {
      if (!this.hasAdd) return;
      this.detailShow = false;
      let delKeys = this.detailData.unitQty + '&' + this.detailData.goodsName + '&' + this.detailData.goodsUuid +
					'&' + this.detailData.unit +
					'&' + this.detailData.price + '&' + this.detailData.sourceAddr + '&' + this.detailData.toAddr +
					'&' + this.detailData.getNode + '&' + this.detailData.propSubtype + '&' + this.detailData
        .goodsRegUuid +
					'&' + this.detailData.checkResult;
      this.goodsList = this.goodsList.filter(itm => {
        let keys = itm.unitQty + '&' + itm.goodsName + '&' + itm.goodsUuid + '&' + itm.unit + '&' + itm
          .price +
						'&' + itm.sourceAddr + '&' + itm.toAddr + '&' + itm.getNode + '&' +
						itm.propSubtype + '&' + itm.goodsRegUuid + '&' + itm.checkResult;
        if (keys == delKeys) {
          return false;
        }
        return true;
      });
      this.$refs['mescrollRef0'].resetList(false);
      this.$modal.alert("移除后需要保存生效,是否立即保存?", "提示", () => {
        this.saveGoods();
      }, "确定", true);
    },
    changeKeyWord(val) {
      this.$refs['mescrollRef0'].resetList(false);
    },
    refreshData(all) {
      this.keyWord = "";
      this.showAll = all;
      this.$refs['mescrollRef0'].resetList(true);
    },
    getDicName(keyword, code) {
      return this.$u.dic.getDicNameByKeyCode(keyword, code);
    },
    loadData(page, isNeedRefresh) {
      return new Promise((resolve, reject) => {
        if (this.dataFromInit) {
          if (isNeedRefresh) {
            this.dataFromInit().then(rp => {
              this.goodsList = [...rp.data,];
              let tmpList = [];
              if (this.$u.test.isEmpty(this.keyWord) || !this.showSearch) {
                tmpList = [...this.goodsList,];
              } else {
                tmpList = this.goodsList.filter(itm => {
                  if (itm.goodsName.indexOf(this.keyWord) != -1) {
                    return true;
                  }
                  return false;
                });
              }
              if (rp.noPage == 1) {
                resolve({
                  data: [...tmpList,],
                  totalCount: tmpList.length,
                });
              } else {
                resolve({
                  data: [...tmpList,],
                  totalCount: rp.total,
                });
              }
              this.$emit("needRefresh", true);
            });
          } else {
            let tmpList = [];
            if (this.$u.test.isEmpty(this.keyWord) || !this.showSearch) {
              tmpList = [...this.goodsList,];
            } else {
              tmpList = this.goodsList.filter(itm => {
                if (itm.goodsName.indexOf(this.keyWord) != -1) {
                  return true;
                }
                return false;
              });
            }
            resolve({
              data: [...tmpList,],
              totalCount: tmpList.length,
            });
            this.$emit("needRefresh", true);
          }
        } else {
          if (isNeedRefresh) {
            let param = {
              ...this.params,
            };
            this.$emit("needRefresh", true);
            param.isAll = this.showAll ? "1" : "0";
            caseService.caseGoodsList(param).then(res => {
              if (res.success) {
                if (this.params.justUnUse == 'true') { // 在先保书中只有未北使用的数据才会显示
                  this.goodsList = [...res.data.filter(itm => {
                    return this.$u.test.isEmpty(itm.goodsRegUuid);
                  }),];
                } else {
                  this.goodsList = [...res.data,];
                }
                let tmpList = [];
                if (this.$u.test.isEmpty(this.keyWord) || !this.showSearch) {
                  tmpList = [...this.goodsList,];
                } else {
                  tmpList = this.goodsList.filter(itm => {
                    if (itm.goodsName.indexOf(this.keyWord) != -1) {
                      return true;
                    }
                    return false;
                  });
                }
                if (tmpList.length > (page.size * (page.num - 1))) {
                  let s = (page.size * (page.num - 1));
                  let len = tmpList.length - s;
                  if (len > page.size) {
                    resolve({
                      data: tmpList.slice(s, s + page.size),
                      totalCount: tmpList.length,
                    });
                  } else {
                    resolve({
                      data: tmpList.slice(s),
                      totalCount: tmpList.length,
                    });
                  }
                } else {
                  resolve({
                    data: [],
                    totalCount: 0,
                  });
                }
              } else {
                this.$u.toast('查询失败');
                resolve({
                  data: [],
                  totalCount: 0,
                });
              }
            }).catch(err => {
              console.log(err);
              this.$u.toast('查询失败');
              resolve({
                data: [],
                totalCount: 0,
              });
            });
          } else {
            let tmpList = [];
            if (this.$u.test.isEmpty(this.keyWord) || !this.showSearch) {
              tmpList = [...this.goodsList,];
            } else {
              tmpList = this.goodsList.filter(itm => {
                if (itm.goodsName.indexOf(this.keyWord) != -1) {
                  return true;
                }
                return false;
              });
            }
            if (tmpList.length > (page.size * (page.num - 1))) {
              let s = (page.size * (page.num - 1));
              let len = tmpList.length - s;
              if (len > page.size) {
                resolve({
                  data: tmpList.slice(s, s + page.size),
                  totalCount: tmpList.length,
                });
              } else {
                resolve({
                  data: tmpList.slice(s),
                  totalCount: tmpList.length,
                });
              }
            } else {
              resolve({
                data: [],
                totalCount: 0,
              });
            }
          }
        }
      });
    },
    delTmp(itm) {
      this.goodsList = this.goodsList.filter(itp => {
        return itm.goodsDtlUuid != itp.goodsDtlUuid;
      });
      this.$refs['mescrollRef0'].resetList(false);
    },
    updateBackState(param) {
      if (param.refresh) {
        this.refreshData(false);
      }
    },
    setDataList(rp){
      this.goodsList = [...rp.data,];
      let tmpList = [];
      if (this.$u.test.isEmpty(this.keyWord) || !this.showSearch) {
        tmpList = [...this.goodsList,];
      } else {
        tmpList = this.goodsList.filter(itm => {
          if (itm.goodsName.indexOf(this.keyWord) != -1) {
            return true;
          }
          return false;
        });
      }
      if (rp.noPage == 1) {
        this.$refs['mescrollRef0'].listDatas = this.$u.deepClone(tmpList);
      } else {
        this.$refs['mescrollRef0'].listDatas = this.$u.deepClone(tmpList);
      }
      this.$emit("needRefresh", true);
    },
    getListHeight() {
      if (this.showSearch) {
        return (this.height - 76 - 50 - uni.upx2px(104)) + "px";
      } else {
        return (this.height - 76 - 50) + "px";
      }
    },
    /**
			 * 合并数据方法
			 * @param {Object} cb 回调函数,，可以不填
			 */
    mergeData(cb) {
      this.$modal.showLoading('正在合并数据...');
      let p = new Promise((resolve, reject) => {
        let tmpList = this.$u.deepClone(this.goodsList);
        let mergeObj = {};
        tmpList.forEach(itm => {
          // goodsRegUuid 加上的原因是 有值表示该数据一被使用不能再操作了
          let keys = itm.unitQty + '&' + itm.goodsName + '&' + itm.goodsUuid + '&' + itm
            .unit + '&' + itm.price +
							'&' + itm.sourceAddr + '&' + itm.toAddr + '&' + itm
            .getNode + '&' + itm.propSubtype + '&' + itm.goodsRegUuid + '&' + itm
            .checkResult;
          if (mergeObj[keys]) {
            let tmp = mergeObj[keys];
            tmp.push(itm);
          } else {
            let tmp = [];
            tmp.push(itm);
            mergeObj[keys] = tmp;
          }
        });
        let newGoodList = [];
        for (let k in mergeObj) {
          let ar = mergeObj[k];
          let op;
          for (let i = 0; i < ar.length; i++) {
            if (i == 0) {
              op = ar[i];
              try {
                op.qty = Number(op.qty);
                op.price = Number(op.price);
              } catch (er) {
                op.qty = 0;
                op.price = 0;
                console.log(er)
              }
            } else {
              try {
                op.qty += Number(ar[i].qty);
                op.amt = op.qty * Number(op.price);
              } catch (er) {
                op.qty = 0;
                op.amt = 0;
                console.log(er)
              }
            }
          }
          if (op) newGoodList.push(op);
        }
        resolve(newGoodList);
      });
      p.then(res => {
        this.$modal.hideLoading();
        if (res.length == 0 && this.goodsList.length > 0) {
          // 则表示合并出错了
          this.$u.toast('合并出错了');
          return;
        }
        this.goodsList = [...res,];
        this.keyWord = '';
        this.$refs['mescrollRef0'].resetList(false);
        cb && cb();
      });
    },
  },
}
</script>

<style lang="scss" scoped>
	@import "../case_common.scss";

	.page {
		padding: 0;
	}

	.total-tip {
		color: $u-tips-color;

		text {
			color: $u-type-warning;
			margin-left: 10rpx;
			margin-right: 10rpx;
		}
	}

	.flat-btn {
		position: fixed;
		bottom: 50rpx;
		margin: auto;
		left: 60rpx;
		right: 60rpx;
		z-index: 88;
	}

	.m-is-require {
		color: red;
		margin-left: -8px;
		font-size: 14px;
	}

	.border-left {
		border-left: 1px solid rgb(228, 231, 237);
	}

	.border-Top {
		border-top: 1px solid rgb(228, 231, 237);
	}

	.nwidth {
		width: calc(100% - 80rpx);
	}

	/deep/.u-td {
		white-space: inherit !important;
		height: auto !important;
		line-height: 25px;
	}
</style>
